package com.companyName.common.redis;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import redis.clients.jedis.HostAndPort;

public abstract class AbsJedisFactory {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	protected RedisConfig redisConfig;
	
	protected Pattern addressPattern = Pattern.compile("^.+[:]\\d{1,5}\\s*(;.+[:]\\d{1,5}\\s*)*[;]?\\s*$");
	
	protected Set<HostAndPort> parseHostAndPort(String addressContent) throws Exception {
		try {
			if (StringUtils.isBlank(addressContent)) {
				throw new IllegalArgumentException("redis 连接地址配置不合法");
			}
			boolean result = addressPattern.matcher(addressContent).matches();
			if (!result) {
				throw new IllegalArgumentException("redis 连接地址配置不合法");
			}
			Set<HostAndPort> hostAndPortSet = new HashSet<HostAndPort>();
			String[] addressArrays = addressContent.split(",");
			for (String address : addressArrays) {
				String[] ipAndPort = address.trim().split(":");
				String ip = ipAndPort[0].trim();
				String port = ipAndPort[1].trim();
				HostAndPort hap = new HostAndPort(ip, Integer.parseInt(port));
				hostAndPortSet.add(hap);
			}
			return hostAndPortSet;
		} catch (IllegalArgumentException ex) {
			logger.error("parse redis host and port error", ex);
			throw ex;
		} catch (Exception ex) {
			logger.error("parse redis host and port error", ex);
			throw new Exception("初始化jedis失败", ex);
		}
	}
	
	public void setRedisConfig(RedisConfig redisConfig) {
		this.redisConfig = redisConfig;
	}

}
